import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QFont
from PyQt5.QtCore import Qt, pyqtSignal


class signal_application(QWidget):
    def __init__(self):
        super(signal_application, self).__init__()
        self.line1 = QLineEdit()
        self.gui_init()

    def gui_init(self):
        self.setWindowTitle("多页面通信实验")
        # 经实验, 不调用下句就自适应界面大小
        self.resize(400, 300)

        label1 = QLabel("多应用通信实验")
        label1.setAlignment(Qt.AlignCenter)
        label1.setFont(QFont("楷体", 20, QFont.ExtraBold))

        label2 = QLabel("当前状态")
        label2.setFont(QFont("宋体", 12, QFont.Bold))

        self.line1.setText('这是一个空白输入框')

        layout2 = QHBoxLayout()
        layout2.addWidget(label2)
        layout2.addWidget(self.line1)

        btn1 = QPushButton("创建子页面")
        btn1.clicked.connect(self.btn1_cb)
        btn2 = QPushButton("关闭子页面")
        btn2.clicked.connect(self.btn2_cb)

        layout3 = QHBoxLayout()
        layout3.addWidget(btn1)
        layout3.addWidget(btn2)

        layout1 = QVBoxLayout()
        # 如果不设置主界面的size, addStretch就没有效果
        layout1.addStretch(1)
        layout1.addWidget(label1)
        # 这里是增加上下行间的空白距离, 貌似单位是像素
        layout1.addSpacing(10)
        layout1.addLayout(layout2)
        layout1.addSpacing(10)
        layout1.addLayout(layout3)
        layout1.addStretch(1)

        self.setLayout(layout1)

    def btn1_cb(self):
        print("btn1")
        self.child = child_widget()
        # 先绑定, 之后传的signal才有用
        self.child.my_signal.connect(self.line_info)
        self.child.setWindowTitle("创建的子窗口")
        self.child.show()

    def btn2_cb(self):
        print("btn2")
        try:
            self.child.close()
            # 经调用得知没有下面这句也能成功, 说明signal.connect只要调用一次就行
            self.child.my_signal.connect(self.line_info)
        # 这里防止没有创建子界面却关闭子界面
        except:
            self.line1.setText('子界面不存在!')

    def line_info(self, str_t):
        if str_t == 'create':
            self.line1.setText("子界面被创建")
        elif str_t == 'close':
            self.line1.setText("子界面被关闭")



class child_widget(QWidget):
    # pyqtSignal类创建的参数表明传入参数类型
    my_signal = pyqtSignal(str)

    def __init__(self):
        super(child_widget, self).__init__()
        self.resize(300, 200)
        self.my_signal.emit('create')
        # 标题改变就调用回调函数
        self.windowTitleChanged.connect(
            lambda: self.my_signal.emit('create'))

    def closeEvent(self, event):
        self.my_signal.emit('close')


if __name__ == "__main__":
    app = QApplication(sys.argv)
    tmp = signal_application()
    tmp.show()
    sys.exit(app.exec_())
